package com.toket.android.pushme.parser;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Iterator;

import org.json.JSONArray;
import org.json.JSONObject;

import com.toket.android.pushme.info.ContentInfo;

public class JSONParser {

	private String path;
	private String jsonData;
	private JSONObject jsonObj;
	private JSONArray jsonArr;
	public JSONParser(String path){
		this.path = path;
	}
	
	public boolean connectInputStream(){
		String result = getHttpData(path);
//		System.out.println("result = " + result);
		
		if(result != "" || !result.equalsIgnoreCase("")){
			jsonData = result;
			return true;
		}else{
			jsonData = "";
			return false;
		}
	}
	
	public void setJsonData(String jsonData){
		this.jsonData = jsonData;
	}
	
	public boolean feedLoginData(){
		boolean result = false;
		try {
			jsonObj = new JSONObject(jsonData);
			if(jsonObj.length() > 0){
				result = jsonObj.getBoolean("result");
			}
		} catch (Exception e) {
			// TODO: handle exception
			System.out.println("##### ERROR feedLogShareInfo ######");
			return false;
		}
		return result;
	}
	
	public ArrayList<ContentInfo> feedContentInfo(){
		ArrayList<ContentInfo> info = new ArrayList<ContentInfo>();
		
		try {
			if (jsonData == null || jsonData.equals(null)
					|| jsonData.equalsIgnoreCase("null") || jsonData.equalsIgnoreCase("[]")
					|| jsonData.equals("") || jsonData.length() == 0) {
				return info;
			}
			jsonArr = new JSONArray(jsonData);
			for(int i = 0; i < jsonArr.length(); i++){
				ContentInfo item = new ContentInfo();
				
				JSONObject data = jsonArr.getJSONObject(i);
				Iterator keys = data.keys();

			    while(keys.hasNext()) {
			    	String key = (String) keys.next();
			    	if(key.equalsIgnoreCase("id")){
			    		item.setId(data.getString(key));
			    	}
			    	else if(key.equalsIgnoreCase("room_id")){
			    		item.setRoom_id(data.getString(key));
			    	}
			    	else if(key.equalsIgnoreCase("Equipment")){
			    		String value = data.getString(key);
			    		if(value.startsWith(",")){
			    			value = value.replaceFirst(",", "");
			    		}
			    		item.setEquipment(value);
			    	}
			    	else if(key.equalsIgnoreCase("period_start")){
			    		item.setPeriod_start(data.getString(key));
			    	}
			    	else if(key.equalsIgnoreCase("period_end")){
			    		item.setPeriod_end(data.getString(key));
			    	}
			    }
			    
			    info.add(item);
			}
		} catch (Exception e) {
			// TODO: handle exception
			info = null;
			System.out.println("##### ERROR feedContentInfo ######");
		}
		
		return info;
	}
	
	//////////////////////////////////////////////////////////////
	
	private static String getHttpData(String url) {
		System.out.println("URL Connected ===>>> " + url);
		String result = null;
		int timeOutMS = 1000*10;
		
		try {
			URL myURL = new URL(url);
			URLConnection ucon = myURL.openConnection();
			ucon.setConnectTimeout(timeOutMS);
			InputStream is = ucon.getInputStream();
			result = convertStreamToString(is);
			is.close();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			result = "";
			return result;
		}

		return result;
	}
	
	private static String convertStreamToString(InputStream is) {

		  StringBuilder sb = new StringBuilder();

		  try {
		   BufferedReader reader = new BufferedReader(new InputStreamReader(
		     is, "UTF-8"));
		   String line = null;
		   try {
		    while ((line = reader.readLine()) != null) {
		     sb.append(line + "\n");
		    }
		   } catch (IOException e) {
		    e.printStackTrace();
		   } finally {
		    try {
		     is.close();
		    } catch (IOException e) {
		     e.printStackTrace();
		    }
		   }
		  } catch (Exception e) {

		  }

		  return sb.toString();
	}

	//////////////////////////////////////////////////////////////
}
